const Koa = require("koa");
const KoaRouter = require("koa-router");
const koabodyparser = require("koa-bodyparser");
const { query, passwordEncoder } = require("./util");

const app = new Koa();
const router = new KoaRouter();

// 加载解析请求体的中间件
app.use(koabodyparser());

// register 注册
router.post("/register", async (ctx) => {
    // 解析请求体
    const { username, password, nickname } = ctx.request.body;

    // 非空校验
    if (!username || !password || !nickname) {
        ctx.body = {
            code: 400, // Bad Request
            message: "缺少必须参数",
        };
        return;
    }

    // 查询用户表，该用户名是否存在
    let res = await query("select id from user where username = ?", [username]);
    if (res.length > 0) {
        ctx.body = {
            code: 403, // ForBidden 禁止的操作
            message: "用户已注册",
        };
        return;
    }

    // 可以注册了
    res = await query(
        "insert into user (username, password, nickname) values (?, ?, ?)",
        [username, passwordEncoder(password), nickname]
    );

    // 是否插入成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500, // Internal Server 服务器异常
            message: "用户注册失败",
        };
        return;
    }

    // 注册成功
    ctx.body = {
        code: 201,
        message: "用户注册成功",
    };
});

// login 登录
router.post("/login", async (ctx) => {
    ctx.body = "登录接口";
});

// 加载路由中间件
app.use(router.routes());

// 监听端口，启动服务
app.listen(9000, () => {
    console.log("Koa server running at http://localhost:9000");
});
